package cn.controller;

import cn.entity.Users;
import cn.service.UsersService;
import cn.util.JWTUtil;
import cn.util.PageBean;
import cn.util.ServerResponse;
import cn.util.UsersLoginAnno;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mysql.cj.util.StringUtils;

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/users")
public class UsersController {
    @Autowired
    UsersService usersService;


    @RequestMapping("getOpenId")
    public String getUserInfo(@RequestParam(name = "code") String code)
            throws Exception {
        Map<String, Object> rtnMap = new HashMap<String, Object>();
        String url = "https://api.weixin.qq.com/sns/jscode2session";
        url += "?appid=wx7ccf7b71c7621821";// 自己的appid
        url += "&secret=859718b8cf9d5638789af89a96b39776";// 密匙
        url += "&js_code=" + code;
        url += "&grant_type=authorization_code";
        System.out.println(url);
        byte[] res = null;
        HttpClient httpclient = new DefaultHttpClient();
        HttpGet httpget = new HttpGet(url);
        HttpResponse response = null;
        try {
            response = httpclient.execute(httpget);
            res = IOUtils.toByteArray(response.getEntity().getContent());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (httpget != null) {
                httpget.abort();
            }
            httpclient.getConnectionManager().shutdown();
        }
        JSONObject jo = JSON.parseObject(new String(res, "utf-8"));
        String openid = jo.getString("openid");
        System.out.println(openid);
        return openid;
    }
    //2、openID存入数据库
    @RequestMapping("saveopenid")
    public ServerResponse saveopenid(String openId,String userName) {
        QueryWrapper<Users> wrapper = new QueryWrapper<Users>();
        wrapper.eq("openId", openId);
        List<Users> usersList = usersService.list(wrapper);
        if(usersList.size()==0){//如果不存在就存入
            Users users=new Users();
            users.setUsername(userName);
            users.setName(userName);
            users.setPassword("123456");
            users.setOpenId(openId);
            usersService.save(users);
        }
        return new ServerResponse("0", "添加成功!",0L,openId);
    }
    //3、前台登陆
    @RequestMapping("login")
    public ServerResponse login(String openId) {
        QueryWrapper<Users> wrapper = new QueryWrapper<Users>();
        wrapper.eq("openId", openId);
        Map<String, Object> data = new HashMap<String, Object>();
        Users users = usersService.getOne(wrapper);
        System.out.println(openId);
        if (users != null) {
            System.out.println(users);
            // 生成token
            String token = JWTUtil.generateToken(users.getId() + "",
                    users.getOpenId());
            data.put("token", token);
            data.put("users", users);
            return new ServerResponse("0", "登录成功!",0L, data);
        } else {
            return new ServerResponse("1", "登陆失败!");
        }
    }

    //JSON
    @RequestMapping("list")
    @UsersLoginAnno
    public ServerResponse list(Integer page, Integer limit,String name){
        //验证token
        QueryWrapper<Users> wrapper=new QueryWrapper<Users>();
        wrapper.eq("isdel",0);
        if(!StringUtils.isNullOrEmpty(name)){
            wrapper.like("name",name);
        }
        IPage<Users> page_list=new Page<Users>(page,limit);
        page_list=usersService.page(page_list,wrapper);
        long count=page_list.getTotal();
        List<Users> list=page_list.getRecords();
        return new ServerResponse("0","操作成功",count,list);
    }

    @RequestMapping("jsonlist")
    //@UsersLoginAnno
    public ServerResponse jsonlist(){
        //验证token
        QueryWrapper<Users> wrapper=new QueryWrapper<Users>();
        wrapper.eq("isdel",0);
        wrapper.eq("role",0);
        List<Users> list=usersService.list(wrapper);
        return new ServerResponse("0","操作成功",0L,list);
    }

    @RequestMapping("list2")
   // @UsersLoginAnno
    public ServerResponse list2(@RequestBody Map<String,Integer> params){
        QueryWrapper<Users> wrapper=new QueryWrapper<Users>();
        wrapper.eq("isdel",0);
        IPage<Users> page_list=new Page<Users>(params.get("page"),params.get("limit"));
        page_list=usersService.page(page_list,wrapper);
        long count=page_list.getTotal();
        List<Users> list=page_list.getRecords();
        return new ServerResponse("0","操作成功",count,list);
    }

//    @RequestMapping("login")
//    public ServerResponse login(String username, String password, String vcode,Integer role){
//        // 获取验证码
//        //String code = (String) session.getAttribute("code");
//       // if (code != null && code.equalsIgnoreCase(vcode)) {
//            QueryWrapper<Users> wrapper=new QueryWrapper<Users>();
//            wrapper.eq("username",username);
//            wrapper.eq("password",password);
//            wrapper.eq("role",role);
//            wrapper.eq("isdel",0);
//            List<Users> list=usersService.list(wrapper);
//            if(list.size()>0){
//                Users users=list.get(0);
//                //生成token
//                String token=JWTUtil.generateToken(users.getId()+"",users.getUsername());
//                users.setToken(token);
//                return new ServerResponse("0","登陆成功!",1L,users);
//            }else{
//                return new ServerResponse("1","用户名或密码错误!");
//            }
////        }else{
////            return  new ServerResponse("1", "验证码错误!");
////        }
//    }

    @RequestMapping("add")
    public ServerResponse add(@RequestBody Users users){
        //验证token
        users.setRole(1);
        users.setIsdel(0);
        boolean flag=usersService.save(users);
        if(flag){
            return new ServerResponse("0","操作成功!");
        }else{
            return new ServerResponse("1","操作失败!");
        }
    }

    @RequestMapping("update")
    public ServerResponse update(@RequestBody Users users){
        boolean flag=usersService.updateById(users);
        if(flag){
            return new ServerResponse("0","操作成功!");
        }else{
            return new ServerResponse("1","操作失败!");
        }
    }

    @RequestMapping("delete")
    public ServerResponse delete(String ids){
        if(ids!=null){
            String[] sid=ids.split(",");
            for(int i=0;i<sid.length;i++){
                Integer id=Integer.parseInt(sid[i]);
                Users users=usersService.getById(id);
                users.setIsdel(1);
                boolean flag=usersService.updateById(users);
            }
        }


        return new ServerResponse("0","操作成功!");

    }
}
